package com.fanco.learn_datastruct_leetcode.jvm;

import java.lang.ref.SoftReference;

/**
 * @author qiaowang 2021/8/24
 * 软引用 Demo
 */
public class SoftReferenceDemo {
    public static void main(String[] args) {
        softReferenceEnough();

        System.out.println("================");
        System.out.println("================");
        System.out.println("================");

        softReferenceNotEnough();
    }

    /**
     * 设置 -Xms5m -Xmx5m
     */
    private static void softReferenceNotEnough() {
        // 创建一个 强引用
        Object o1 = new Object();

        // 创建一个软引用
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println(o1);
        System.out.println(softReference);

        o1 = null;

        try {
            byte[] bytes = new byte[50 * 1024 * 1024];
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.gc();
            System.out.println(o1);
            System.out.println(softReference.get());
        }

    }

    private static void softReferenceEnough() {
        // 创建一个 强引用
        Object o1 = new Object();

        // 创建一个软引用
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println(o1);
        System.out.println(softReference);

        o1 = null;

        System.gc();
        System.out.println(o1);
        System.out.println(softReference.get());

    }
}
